package com.allwees.bs.c.module.user.mapper;

import com.allwees.bs.c.module.base.mapper.IMapper;
import com.allwees.bs.c.module.sys.entity.RegionEntity;
import com.allwees.bs.c.module.sys.repository.RegionRepository;
import com.allwees.bs.c.module.user.dto.ShippingAddressDTO;
import com.allwees.bs.c.module.user.entity.ShippingAddressEntity;
import com.allwees.bs.core.modelbase.page.PageParams;
import com.allwees.bs.core.modelbase.page.PaginateDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ShippingAddressMapper implements IMapper<ShippingAddressDTO, ShippingAddressEntity> {

    @Autowired
    private RegionRepository regionRepository;

    @Override
    public ShippingAddressDTO entity2DTO(ShippingAddressEntity entity) {
        if (entity == null) {
            return null;
        }
        return new ShippingAddressDTO(entity);
    }

    public PaginateDTO<ShippingAddressDTO> entity2DTO(List<ShippingAddressEntity> entityList, int total, PageParams pageParams) {
        if (entityList == null) {
            return PaginateDTO.of(0, 0, pageParams);
        }
        PaginateDTO<ShippingAddressDTO> shippingAddressPaginateDTO = PaginateDTO.of(total, entityList.size(), pageParams);
        List<ShippingAddressDTO> addressDTOList = new ArrayList<>();
        entityList.forEach(entity -> {
            // 将 region id 保存至 ShippingAddressDTO region 字段
            ShippingAddressDTO dto = new ShippingAddressDTO(entity);
            RegionEntity region = regionRepository.findCountryByName(dto.getCountry());
            if (region != null) {
                dto.setRegion(String.valueOf(region.getId()));
            }
            addressDTOList.add(dto);
        });
        shippingAddressPaginateDTO.setResults(addressDTOList);
        return shippingAddressPaginateDTO;
    }
}
